<template>
    <el-dialog :model-value="show" title="分配角色" @close="emit('OpShow', false)">
        <el-select v-model="list" placeholder="请选择" multiple style="width:200px">
            <el-option v-for="item in roles" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
        </el-select>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="NosubmitForm">取消</el-button>
                <el-button type="primary" @click="submitForm">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang='ts'>import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, watch } from 'vue';
import { getRoleListApi, getRolesByUserIdApi, updateUserRolesApi } from './api';

const props = defineProps({
    show: {
        type: Boolean,
        default: true
    },
    id: {
        type: Number,
        default: 0
    }
})

const emit = defineEmits(['OpShow'])


// 全部角色数据
const roles = ref<{ value: number, label: string }[]>([])
// 请求全部角色数据
getRoleListApi().then(res => {
    if (res.code === 200) {
        roles.value = res.data.map((item) => ({
            value: item.id,
            label: item.name,
        }))
    }
})
// 指定用户角色数据
const list = ref<number[]>([])
// 获取指定用户的角色
watch(() => props.id, () => {
    if (props.id !== 0) {
        getRolesByUserIdApi(props.id).then((res) => {
            if (res.code === 200) {
                list.value = res.data.map((item) => item.id)
            }
        })
    }
})

// 点击确定
const submitForm = () => {
    ElMessageBox.confirm('确定要添加用户吗', '添加用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        // 修改用户角色请求(用户id+角色id)
        updateUserRolesApi(props.id, list.value).then((res) => {
            if (res.code === 200) {
                emit("OpShow", true);
                ElMessage.success("修改成功")
                // 清空表单
                list.value = []
            }
        })
    }).catch(() => {
        ElMessage.error('修改失败,请重新修改')
    })


}
// 点击取消
const NosubmitForm = () => {
    // 把dialog关闭
    // 刷新数据
    emit("OpShow", false);
    // 清空表单
    list.value = []
}

</script>
<style lang="less" scoped>

</style>